【发布时间】:2014-08-21 07:10:47
【问题描述】:
我正在尝试创建一个可以在我的活动布局中使用的自定义小部件。我为扩展 View 的小部件创建了一个类。
import android.app.Service;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import be.robinj.ubuntu.R;
public class AppLauncher extends View
{
private String name;
private String description;
private boolean special;
private AppIcon icon;
private View view;
public AppLauncher (Context context, AttributeSet attrs)
{
super (context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Service.LAYOUT_INFLATER_SERVICE);
this.view = inflater.inflate (R.layout.widget_applauncher, null, false);
TypedArray styleAttrs = context.getTheme ().obtainStyledAttributes (attrs, R.styleable.AppLauncher, 0, 0);
this.name = styleAttrs.getString (R.styleable.AppLauncher_label);
this.description = styleAttrs.getString (R.styleable.AppLauncher_description);
this.special = styleAttrs.getBoolean (R.styleable.AppLauncher_special, false);
this.icon = new AppIcon (styleAttrs.getDrawable (R.styleable.AppLauncher_icon));
}
...
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="64dp"
android:layout_height="64dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffff9243"
android:layout_margin="6dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/launcher_icon_bg">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imgIcon"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="AppLauncher">
<attr name="label" format="string" />
<attr name="description" format="string" />
<attr name="icon" format="integer" />
<attr name="special" format="boolean" />
</declare-styleable>
</resources>
没关系,但 Java 代码最好只包含逻辑部分。 我不知道如何指定应该为我的自定义视图/小部件使用哪个布局 XML 文件。 Inflating 布局大概会加载它。不过,inflate () 方法需要第二个和第三个参数。我能找到的每个示例都显示this 作为第二个参数传递,但第二个参数应该是ViewGroup,而this 扩展View。我从哪里神奇地得到这个必需的ViewGroup 对象?传递 null 和 false 不会引发错误,但它也不会做任何其他事情(运行应用程序时没有任何显示)。
【问题讨论】:
标签: java android xml android-layout