我在没有xml文件的情况下动态创建片段现在我想从父活动中调用fragement中的方法,所以我怎么能这样做才能让任何人知道它,我发现很多问题但他们正在使用xml < / p>
Fragmentactivity
public class HomeActivity extends FragmentActivity implements OnClickListener {
public static final String TAG = HomeActivity.class.getSimpleName();
PageIndicator mIndicator;
//Spinner spinner1;
ImageView serversetting,dropdown;
TextView selectrange;
int num,counter=0;
String url,apiUser,apipass,TestAccount;
/* public static HomeActivity newInstance() {
return new HomeActivity();
}*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_parent);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
selectrange=(TextView)findViewById(R.id.selectrange);
serversetting=(ImageView)findViewById(R.id.settingsserver);
dropdown=(ImageView)findViewById(R.id.dropdown);
mViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mViewPager);
selectrange.setOnClickListener(this);
dropdown.setOnClickListener(this);
serversetting.setOnClickListener(this);
/*spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Current Month");
list.add("Last Month");
list.add("Last 5 Days");
list.add("Last 10 Days");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_layout,R.id.spinnerTarget,list);
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
serversetting.setOnClickListener(this);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});*/
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 3;
}
@Override
public Fragment getItem(int position) {
/* Bundle args = new Bundle();
args.putInt(TextViewFragment.POSITION_KEY, position);
return TextViewFragment.newInstance(args);*/
Fragment f=new Fragment();
switch(position) {
case 0:
f= new SalesGraphFragment();
break;
case 1:
f=new OrderGraphFragment();
break;
case 2:
f=new UserGraphFragment();
break;
}
return f;
}
/*@Override
public CharSequence getPageTitle(int position) {
return "Fragment # " + position;
}*/
}
@Override
protected void onStart()
{
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onStop()
{
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
void SelectRangeDialog()
{
final CharSequence[] list = {"All time","Current Month","Last Month","Today","YesterDay"};
AlertDialog.Builder alert = new AlertDialog.Builder(HomeActivity.this);
if(counter==0)
{
num=1;
counter++;
}
alert.setTitle("Range");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
//selectrange.setText(list[which]);
// new ChangeStatusAsync().execute();
}
});
/*if(status.equals("Order Pending"))
num=0;
else if(status.equals("Upfront Received"))
num=1;
else if(status.equals("Payment Complete"))
num=2;*/
alert.setSingleChoiceItems(list,num, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//newstatus=list[which].toString();
selectrange.setText(list[which]);
num=which;
}
});
alert.show();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.settingsserver:
Intent settings=new Intent(HomeActivity.this,SettingsActivity.class);
startActivity(settings);
break;
case R.id.selectrange:
SelectRangeDialog();
break;
case R.id.dropdown:
SelectRangeDialog();
break;
default:
break;
}
}
}
片段
public class SalesGraphFragment extends Fragment {
public static final String POSITION_KEY = "com.burnside.embeddedfragmenttest.POSITION";
public static final String TITLE_KEY = "com.burnside.embeddedfragmenttest.TITLE";
Object saleData[];
String strSales="";
TextView txt;
public Object b;
List array;
public Object [] objects;
public static SalesGraphFragment INSTANCE;
LinearLayout layout;
String sessionId,url,amount,apiUser,apipass,TestAccount;
MagentoStoreLogin sales=new MagentoStoreLogin();
public ProgressDialog order_dialog;
public static SalesGraphFragment newInstance(Bundle args) {
SalesGraphFragment fragment = new SalesGraphFragment();
fragment.setArguments(args);
ProgressDialog order_dialog;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
TestAccount=getActivity().getIntent().getExtras().getString("TestAccount");
if(TestAccount==null)
TestAccount="";
if(TestAccount.equals("TestAccount"))
{
url =getActivity().getIntent().getExtras().getString("defaulturl");
apiUser=getActivity().getIntent().getExtras().getString("defaultapiuser");
apipass=getActivity().getIntent().getExtras().getString("defaultapipass");
System.out.println(url + apipass + apiUser);
}
else
{
url=PreferenceConnector.readString(getActivity(),PreferenceConnector.URL, null);
System.out.println("URL is:"+url);
apiUser=PreferenceConnector.readString(getActivity(),PreferenceConnector.APIUSER, null);
apipass=PreferenceConnector.readString(getActivity(),PreferenceConnector.APIPASS, null);
new saleDetail().execute();
new GraphValue().execute();
System.out.println(url + apipass + apiUser);
}
if(url!=null&&url!="")
{
//Load the first 12 items
// counter=0;
}
else
{
Toast.makeText(getActivity(),"Please do the API settings first", 1).show();
}
}
catch(Exception e)
{
Toast.makeText(getActivity(),"Please do the settings first Exception", 1).show();
// uName.setText("");
// password.setText("");
}
}
public static SalesGraphFragment getSaleInstance()
{
return INSTANCE;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.sales_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(!TestAccount.equals("TestAccount"))
{
GraphViewSeries exampleSeries = new GraphViewSeries(new GraphViewData[] {
new GraphViewData(5, 2.0d)
, new GraphViewData(4, 1.0d)
, new GraphViewData(3, 3.0d) // another frequency
, new GraphViewData(2, 2.0d)
, new GraphViewData(1, 1.0d)
, new GraphViewData(0, 6.0d)
});
// graph with dynamically genereated horizontal and vertical labels
GraphView graphView;
graphView = new LineGraphView(
getActivity() // context
, "" // heading
);
graphView.addSeries(exampleSeries); // data
// LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
// layout.addView(graphView);
// graph with custom labels and drawBackground
((LineGraphView) graphView).setDrawBackground(true);
// custom static labels
// graphView.setHorizontalLabels(new String[] {"2 days ago", "yesterday", "today", "tomorrow"});
// graphView.setVerticalLabels(new String[] {"high", "middle", "low"});
//graphView.addSeries(exampleSeries); // data
//graphView.setViewPort(2, 5);
//graphView.setBackgroundColor(Color.WHITE);
// graphView.set
layout = (LinearLayout) view.findViewById(R.id.salesgraph);
txt=(TextView) view.findViewById(R.id.salesamount);
txt.setText(getData());
layout.addView(graphView);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
inflater.inflate(R.menu.optionmenus, menu);
super.onCreateOptionsMenu(menu, inflater);
}
// Handle click events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutus:
Intent aboutus=new Intent(getActivity(),AboutUs.class);
startActivity(aboutus);
return true;
case R.id.settings:
Intent settings=new Intent(getActivity(),SettingsActivity.class);
startActivity(settings);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public String getData()
{
return strSales;
}
public void setSessionId(String sessionId)
{
this.sessionId=sessionId;
}
public class saleDetail extends AsyncTask<Void,Integer,Object>
{
ProgressBar progressBar;
@Override
protected Object doInBackground(Void... params) {
try
{ if(sessionId==null)
{
sessionId=sales.login(url, apiUser, apipass);
setSessionId(sessionId);
}
b=sales. getSaleInfo(sessionId,url);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Getting Order Error:"+e.getMessage());
//customer_results=null;
}
//}
return b;
}
@Override
protected void onPreExecute()
{
order_dialog = ProgressDialog.show(getActivity(),"Getting Sales Information...", "Please wait while loading", true);
}
protected void onPostExecute(final Object object)
{
order_dialog.dismiss();
if(object!=null)
{
System.out.println("Dismiss Called");
Map<String, Double> mappedData=(Map)object;
Double sales=mappedData.get("Total Sale");
double finalValue = Math.round( sales * 100.0 ) / 100.0;
strSales=""+finalValue;
txt.setText(finalValue+"");
//setData(object);
}
else
{
Toast.makeText(getActivity(),"You Dont have our package", 10).show();
}
}
}
public class GraphValue extends AsyncTask<Void,Integer,Object[]>
{
ProgressBar progressBar;
@Override
protected Object[] doInBackground(Void... params) {
try
{ if(sessionId==null)
{
sessionId=sales.login(url, apiUser, apipass);
setSessionId(sessionId);
}
objects=sales.getGraphValue(sessionId,url);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Getting Order Error:"+e.getMessage());
//customer_results=null;
}
//}
return objects;
}
@Override
protected void onPreExecute()
{
// order_dialog = ProgressDialog.show(getActivity(),"Getting Sales Information...", "Please wait while loading", true);
}
protected void onPostExecute(final Object object[])
{
// order_dialog.dismiss();
// System.out.println("Data length is:"+object.length);
// System.out.println("Dismiss Called");
for(Object obj:object)
{
extractDate(obj);
}
}
private void extractDate(Object obj) {
// TODO Auto-generated method stub
Map map=(Map)obj;
System.out.println(map.get("getCreatedAt"));
}
}
}
答案 0 :(得分:18)
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_holder);
if (fragment instanceof MyFragment)
((MyFragment) fragment).myFragmentMethod();
答案 1 :(得分:2)
我会创建一个扩展Fragment的新抽象类。
SalesGraphFragment,OrderGraphFragment和UserGraphFragment会扩展这个新类,他们会实现你想从活动中调用的方法。
从活动中,您可以通过以下方式调用此方法:
adapter.getItem(X).myMethod();
答案 2 :(得分:1)
在某些情况下,特别是在使用XML定义时......那么这将是:
[your fragment class here] blabla =( [your fragment class here])getSupportFragmentManager()
.findFragmentById(R.id.myfragment_id);
blabla.method_x();