我通过扩展布局类来创建自己的UI组件类。现在不是在字符串xml资源中添加我的自定义属性(如高度,宽度等)作为单独的xml,而是想在Activity
类本身中定义。我不想添加xml,然后在我的代码中从R类引用它。有没有办法在代码本身中定义和访问属性?
答案 0 :(得分:0)
以下是Pro Android 4的代码示例:
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
private LinearLayout nameContainer;
private LinearLayout addressContainer;
private LinearLayout parentContainer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
createNameContainer();
createAddressContainer();
createParentContainer();
setContentView(parentContainer);
}
private void createNameContainer()
{
nameContainer = new LinearLayout(this);
nameContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
nameContainer.setOrientation(LinearLayout.HORIZONTAL);
TextView nameLbl = new TextView(this);
nameLbl.setText("Name: ");
TextView nameValue = new TextView(this);
nameValue.setText("John Doe");
nameContainer.addView(nameLbl);
nameContainer.addView(nameValue);
}
private void createAddressContainer()
{
addressContainer = new LinearLayout(this);
addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
addressContainer.setOrientation(LinearLayout.VERTICAL);
TextView addrLbl = new TextView(this);
addrLbl.setText("Address:");
TextView addrValue = new TextView(this);
addrValue.setText("911 Hollywood Blvd");
addressContainer.addView(addrLbl);
addressContainer.addView(addrValue);
}
private void createParentContainer()
{
parentContainer = new LinearLayout(this);
parentContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
parentContainer.setOrientation(LinearLayout.VERTICAL);
parentContainer.addView(nameContainer);
parentContainer.addView(addressContainer);
}
}
另见更多功能: