1

是否可以将视图添加到片段内的布局。我的片段代码看起来像这样,但我在添加时崩溃了。

我想动态地将视图添加到片段内的线性布局中。

package com.emergreen.goresq;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.SherlockFragment;

public class GRPlacesFragment extends SherlockFragment{

    GRMyPlaces grmp;
    View myview;

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.grpl,
                                         container, false);

            myview = view;
            return view;
        }


     public void addPlaces(context gr)
     {
         grmp = gr;

         LinearLayout ll = (LinearLayout) myview.findViewById(R.id.pid);

         Button button = new Button(grmp);
         button.setText("Testing button");



         ll.addView(button);


     }

}
4

1 回答 1

1

当我将片段用于项目时,请尝试执行以下似乎对我有用的操作:

public class GRPlacesFragment extends SherlockFragment {

...
private View myView;

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.grpl, container, false);

        return myView;
    }


 ...

}

您的变量分配似乎有问题,因为您在使用“view”和“myview”之间进行了更改。

您还应该确保您的两个变量是私有的,因此只能访问这个特定的类。

告诉我这是否有帮助。

于 2013-07-10T21:37:03.870 回答