如何从视图类中获取视图?

时间:2011-09-12 10:18:35

标签: android view android-activity

我是android.i的新开发人员在该视图类中创建了一个视图类我想将字符串数组值应用到textview我的View类如下:

    class MyView extends View
 {
    Context con;
String messages[]=new String[]{"hello","hai","how are you","where are you"};
public MyView(Context context) {
    super(context);
    con=context; 

       for(int i=0;i<3;i++)
     {

         Log.v("messages", "messages"+messages[i]);
     }


     public View getView(int position, View view, ViewGroup vg)
{
    if (view == null)
    {
        // context would be a variable set via the constructor and given
        // by our owner (most likely a ListActivity)
        LayoutInflater inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.view, null);
    }

    // Here you would get the sub-views of your layout and fill them
    TextView msg = (TextView) view.findViewById(R.id.txtmessage);
    msg.setText(messages[position]);
    return view;
}

}

从上面的类我想在活动类

中查看MyView类的视图
     public class ViewActivity extends Activity {



TableRow tbr;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

     tbr=(TableRow)findViewById(R.id.tableRow1);


     MyView mv=new MyView(this);
     tbr.addView(mv);

}

}

从上面的代码我无法查看MyView类

如何获取MyView类的视图

1 个答案:

答案 0 :(得分:2)

您需要将layoutparams设置为您的视图。现在你的视图没有大小。

你需要这样的东西

MyView mv=new MyView(this);
mv.setLayoutParams(new LayoutParams(new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));
tbr.addView(mv);