更改片段活动中的视图

时间:2014-09-15 18:16:49

标签: android android-fragments

我之前尝试了几个答案,但仍然收到错误。我想从片段活动中更改片段中的textView。

我在片段中创建了一个名为change title的方法,并尝试从Fragment Activity中调用它。但是我收到了错误。

片段类

public class Desc extends Fragment {

    String id="26";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View ios = inflater.inflate(R.layout.details_frag, container, false);
        ((TextView)ios.findViewById(R.id.product_label)).setText("A");
        ((TextView)ios.findViewById(R.id.product_id)).setText("26");
        ((TextView)ios.findViewById(R.id.des)).setText("des");
        ((TextView)ios.findViewById(R.id.color)).setText("color");
        changeTitle("Test");
        return ios;
    }

    public void changeTitle (String ptitle) {
        TextView t= (TextView) getView().findViewById(R.id.product_label);
        t.setText(ptitle);
    }
}

片段活动类

public class ProductDetails extends FragmentActivity {

    ViewPager Tab;
    TabPagerAdapter TabAdapter;
    ActionBar actionBar;

    ProgressDialog pdia;

    String id,title,des,color,photo1;
    HttpClient client;
    JSONObject json;
    String URL = "http://wirefreeworld.in/api/find.php?id=";

    Desc frag_desc = (Desc) getSupportFragmentManager().findFragmentById(R.id.desc_frag);
    Desc frag_photo = (Desc) getSupportFragmentManager().findFragmentById(R.id.photo_frag);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);

        Intent get = getIntent();
        id = get.getStringExtra("pid");
        setTitle("Wire Free World : "+ id);

        client = new DefaultHttpClient();
        new Read().execute("title");
        new ReadPhoto1().execute("photo1");

        frag_desc.changeTitle("Testing");

        TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
        Tab = (ViewPager)findViewById(R.id.pager);
        Tab.setOnPageChangeListener(
                new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar = getActionBar();
                        actionBar.setSelectedNavigationItem(position);                    }
                });
        Tab.setAdapter(TabAdapter);
        actionBar = getActionBar();
        //Enable Tabs on Action Bar
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.TabListener tabListener = new ActionBar.TabListener(){
            @Override
            public void onTabReselected(android.app.ActionBar.Tab tab,
                                        FragmentTransaction ft) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
                Tab.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(android.app.ActionBar.Tab tab,
                                        FragmentTransaction ft) {
                // TODO Auto-generated method stub
            }};
        //Add New Tab
        actionBar.addTab(actionBar.newTab().setText("Photos").setTabListener(tabListener));
        actionBar.addTab(actionBar.newTab().setText("Details").setTabListener(tabListener));

    }

    public class Read extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... strings) {
            try {
                String proid = id;
                int pID = Integer.parseInt(proid);
                json = fetchData(pID);
                return json.getString(strings[0]);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdia = new ProgressDialog(ProductDetails.this);
            pdia.setMessage("Loading...");
            pdia.show();
        }

        @Override
        protected void onPostExecute(String s) {
            title =s;
        }
    }

    public class ReadPhoto1 extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... strings) {
            try {
                String proid = id;
                int pID = Integer.parseInt(proid);
                json = fetchData(pID);
                return json.getString(strings[0]);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
           photo1=s;
           pdia.dismiss();
        }
    }

    public JSONObject fetchData(int pid) throws ClientProtocolException, IOException, JSONException{
        StringBuilder url= new StringBuilder(URL);
        url.append(pid);

        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray product = new JSONArray(data);
            JSONObject proData = product.getJSONObject(0);
            return proData;
        } else {
            Toast.makeText(ProductDetails.this, "Error", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

}

logcat的

09-15 23:42:15.638  14032-14032/in.wirefreeworld.wfw D/AndroidRuntime﹕ Shutting down VM
09-15 23:42:15.638  14032-14032/in.wirefreeworld.wfw W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41621ba8)
09-15 23:42:15.648  14032-14032/in.wirefreeworld.wfw E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: in.wirefreeworld.wfw, PID: 14032
    java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wirefreeworld.wfw/info.androidhive.listviewfeed.ProductDetails}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
            at android.app.Activity.setContentView(Activity.java:1929)
            at info.androidhive.listviewfeed.ProductDetails.onCreate(ProductDetails.java:61)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at info.androidhive.listviewfeed.Desc.changeTitle(Desc.java:44)
            at info.androidhive.listviewfeed.Desc.onCreateView(Desc.java:39)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:915)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1099)
            at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1201)
            at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:292)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
            at android.app.Activity.setContentView(Activity.java:1929)
            at info.androidhive.listviewfeed.ProductDetails.onCreate(ProductDetails.java:61)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

堆栈跟踪显示您从getView()调用changeTitleonCreateView调用onCreateViewgetView()应该创建并返回getView()应返回的视图 - 因此在onCreateView完成之前,您不能指望public class Desc extends Fragment { String id="26"; TextView productLabel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View ios = inflater.inflate(R.layout.details_frag, container, false); productLabel = (TextView)ios.findViewById(R.id.product_label); productLabel.setText("A"); ((TextView)ios.findViewById(R.id.product_id)).setText("26"); ((TextView)ios.findViewById(R.id.des)).setText("des"); ((TextView)ios.findViewById(R.id.color)).setText("color"); changeTitle("Test"); return ios; } public void changeTitle (String ptitle) { productLabel.setText(ptitle); } } 返回任何有用的内容。
你可以试试这个:

{{1}}

答案 1 :(得分:0)

使用您正在充气的视图而不是getView() 尝试改变你的changeTitle方法:

  public void changeTitle (View ios, String ptitle) {
        TextView t= (TextView) ios.findViewById(R.id.product_label);
        t.setText(ptitle);
    }