Reputation: 11
In my fragment class i have some buttons so when i click that buttons i want to redirect to another Activity class. How can i use redirection in fragment class?
fragment_services.xml `
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="409dp" >
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="160dp"
android:layout_height="90dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="18dp"
android:background="@drawable/cloud" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>`
ServiceFragment.java
public class ServiceFragment extends Fragment {
private Context CurrentObj=this;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_services, container, false);
final Button backBtn=(Button)findViewById(R.id.button3);
backBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent redirect=new Intent(CurrentObj.getApplicationContext(),Cloud.class);
startActivity(redirect);
}
});
return rootView;
}
}
Cloud.java
public class Cloud extends Activity{
private Context CurrentObj=this;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cloud);
}
}
Upvotes: 0
Views: 8439
Reputation:
If you want to do it using context then do as following
private Context CurrentObj=getActivity();
backBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent redirect=new Intent(CurrentObj,Cloud.class);
CurrentObj.startActivity(redirect);
}
});
Upvotes: 0
Reputation: 8281
You shouldnt forget about your parent activity.
Intent redirect=new Intent(getActivity(),Cloud.class);
getActivity().startActivity(redirect);
Upvotes: 0
Reputation: 1326
backBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent redirect=new Intent(getActivity(),Cloud.class);
getActivity().startActivity(redirect);
}
});
You also need to make sure that your Cloud
class is extending Activity and you have declared your Cloud
Activity in AndroidManifest.xml
.
I also found some little bug in your code. This line private Context CurrentObj=this;
in ServiceFragment
class will cause compiler error because Fragments aren't subclasses of Context or ContextWrappers. You need to change or remove this line from your Fragment.
Upvotes: 4