Search code examples
androidimageviewandroid-imageviewandroid-custom-view

Programatically adding Custom ImageView in MainActivity


I want to dynamically add my custom ImageView to the MainActivity which already contains a EditText such that the whole space under EditText should be covered by ImageView. Then I would draw something on ImageView upon TouchEvent and accordingly output some text to EditText. But nothing is working out with my approach. Please help.
*activity_main.xml*

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/RL"
 >

<EditText
    android:id="@+id/et1"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:ems="10"
    android:inputType="textMultiLine" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {
BondImage BI;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    BI = new BondImage(this);           
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

BondImage.java

public class BondImage extends ImageView{

Canvas c;
Paint p;
Bitmap bm;
float x, y;
public BondImage(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    bm = Bitmap.createBitmap(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT,Config.ARGB_8888);
    RelativeLayout rl = (RelativeLayout)findViewById(R.id.RL);
    rl.addView(this, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    c = new Canvas(bm);
    p = new Paint();
    p.setColor(Color.MAGENTA);
    x = y = 0;
}

public boolean onTouchEvent(MotionEvent me){
    c.drawCircle(x, y, 25, p);   //example
    this.setImageBitmap(bm);
    x ++; y ++;
            /*  and some other stuff  */
    return true;        
}
}

Solution

  • ok, finally I modified my approach ( actually that was what I thought initially, but still I am not satisfied with that )
    I created a static ImageView below the EditText and Used it for handling MotionEvents and drawing directly. For MotionEvent I had to normalize coordinates, as simply using getX and getY would give coordinates relative to whole view But I needed them relative to ImageView .Downside of this approach is that its somewhat slow, thats why I was excusing myself from using it. But right now I have no other approach in my mind to handle both EditText and custom ImageView in the same activity.
    Any suggestions will be greatly appreciated.