これを行うには、1 つまたは 2 つの方法が考えられます。
すべてのアクティビティ レイアウトのルート レイアウトが であることを確認してRelativeLayout
から、必要なパラメーターを使用してビューをビューに追加し、ビューの中央に配置することができます。これは、レイアウトが の最初の子でRelativeLayout
あり、画像が 2 番目の子として追加されるため、最初の子の上に表示されることを意味します。
また
を拡張して、独自のレイアウト マネージャを作成しますViewGroup
。多少の調整が必要になるかもしれませんが、基本的にはこのように表示されるViewGroup
はずです。
public class Article2 extends ViewGroup {
private View layout;
private ImageView theImage;
private Context ctx;
public Article2(Context context,View layout) {
super(context);
ctx = context;
this.layout = layout;
this.addView(layout);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
for(int i = 0;i<this.getChildCount();i++){
final View child = this.getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
setMeasuredDimension(widthSpecSize, heightSpecSize);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layout.layout(left, top, right, bottom);
if(theImage!= null){
theImage.layout(right/2 - theImage.getMeasuredHeight()/2, bottom/2 -theImage.getMeasuredHeight()/2, right/2 + theImage.getMeasuredHeight()/2, bottom/2 + theImage.getMeasuredHeight()/2);
}
}
public void startImage(String url){
theImage = new ImageView(ctx);
new GetImage(url).execute();
}
private class GetImage extends AsyncTask<Void,Void,Boolean>{
String url=null;
public GetImage(String url){
this.url = url;
}
@Override
protected Boolean doInBackground(Void... arg0) {
if(url!=null&&url.length()>0){
try {
theImage.setImageBitmap(BitmapFactory.decodeStream((InputStream)new URL(url).getContent()));
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}else{
return false;
}
}
@Override
protected void onPostExecute(Boolean addView){
if(addView){
addView(theImage);
}
}
}
}
編集
上記のクラスの使用方法を追加するのを忘れていました。
そのonCreate()
ようにコンテンツビューをレイアウトファイルに設定する代わりに
setContentView(R.layout.MyLayout);
代わりにこれを行う
Article2 article2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.MyLayout, null);
article2 = new Article2(this,v);
setContentView(article2);
}
このように、上記の 5 行だけで各アクティビティを機能させることができます。
画像を表示するには、呼び出すだけparentActivity.article2.startImage(url)
で、画面の中央に指定したビューの上に画像が配置されます
1つの注意点として、画像が配置されたら、おそらく使用する必要があるだけで、画像を削除するためにそこに何も入れていarticle2.removeViewAt(1)
ませんが、テストしていません.