How to edit dimension of customview in Android Studio? - java

I want to give custom dimension to custom view but when i open the app, it show me the image in small dimension. In the customview i put a GIF image.
The CustomGifView.java
public class CustomGifView extends View {
private InputStream gifInputStream;
private Movie gifMovie;
private int movieWidth, movieHeight;
private long movieDuration;
private long mMovieStart;
public CustomGifView(Context context) {
super(context);
init(context);
}
public CustomGifView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomGifView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context){
setFocusable(true);
gifInputStream = context.getResources()
.openRawResource(R.drawable.caricamento);
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
#Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
setMeasuredDimension(movieWidth, movieHeight);
}
public int getMovieWidth(){
return movieWidth;
}
public int getMovieHeight(){
return movieHeight;
}
public long getMovieDuration(){
return movieDuration;
}
#Override
protected void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (gifMovie != null) {
int dur = gifMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - mMovieStart) % dur);
gifMovie.setTime(relTime);
gifMovie.draw(canvas, 0, 0);
invalidate();
}
}
The caricamento.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:components="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#398596">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Caricamento in corso..."
android:id="#+id/textView"
android:textColor="#ffffff"
android:layout_marginBottom="37dp"
android:layout_above="#+id/textView4"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tip: Lo sapevi che il QR Scanner rileva automaticamente il codice del tavolo?"
android:id="#+id/textView4"
android:layout_marginBottom="76dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="55dp" />
<com.faddex.ristorante.CustomGifView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/view"
android:layout_above="#+id/textView"
android:layout_centerHorizontal="true" />
As you can see at the end i give 300dp - 300dp but when i open the activity in the smartphone it show always small dimension, even if i change to 10000dp - 10000dp

Related

MP Chart in listView

Please assist me with implementing MP Line Chart in ListView; it works good in recycler view, however it loses its size as I add more than 5 items.
Because of the scroll view, I'm using an expanded listView to reduce issues, yet the chart looks like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="10sp"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="#string/most_active_stocks"/>
<LinearLayout
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="10sp">
<Button
android:layout_width="wrap_content"
android:textSize="10sp"
android:layout_gravity="center"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="#drawable/virtualtrading_button"
android:text="Volume"
android:gravity="center"
android:textColor="#color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textSize="10sp"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#drawable/virtualtrading_button"
android:text="%Turnover"
android:gravity="center"
android:textColor="#color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textSize="10sp"
android:layout_margin="5dp"
android:layout_gravity="center"
android:background="#drawable/virtualtrading_button"
android:text="Range"
android:gravity="center"
android:textColor="#color/black" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.catalyst.maksl.Components.ExpandableHeightListView
android:id="#+id/moverlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:drawSelectorOnTop="false"
android:fadingEdge="vertical"
android:divider="#android:color/transparent"
android:dividerHeight="5dp"
android:fitsSystemWindows="true"
android:listSelector="#00000000"
android:scrollbars="none"
android:smoothScrollbar="true" />
</RelativeLayout>
</LinearLayout>
ExpandableListView Class
public class ExpandableHeightListView extends ListView {
boolean expanded = false;
public ExpandableHeightListView(Context context)
{
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs,int defStyle)
{
super(context, attrs, defStyle);
}
public boolean isExpanded()
{
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded)
{
this.expanded = expanded;
}
}
adapter class :
public class MostActiveStocksAdapter extends BaseAdapter {
private static LineDataSet set1;
public static Drawable drawablePositive = ContextCompat.getDrawable(Logs.globalContext, R.drawable.graph_green_bg);
public static Drawable drawable_negative = ContextCompat.getDrawable(Logs.globalContext, R.drawable.graph_bg);
Context context;
private Double changePercentage;
ArrayList<String> arrayList = new ArrayList<String>();
LayoutInflater mInflater = null;
private ViewHolder holder;
public ArrayList<Entry> values;
public LineData data;
public MostActiveStocksAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.most_active_stocks_listitem, null);
holder = new ViewHolder();
holder.moverSymbolName = (TextView) convertView.findViewById(R.id.moversymbolName);
holder.moverScripName = (AutoResizeTextView) convertView.findViewById(R.id.moversmainSymbolName);
holder.moverLastTradePrice = (TextView) convertView.findViewById(R.id.moverslastTradePrice);
holder.moverchange = (AutoResizeTextView) convertView.findViewById(R.id.moversindexChange);
holder.moverMarket = (TextView) convertView.findViewById(R.id.moverssymbolMarket);
holder.sector = convertView.findViewById(R.id.movertextSector);
holder.nameIcon = convertView.findViewById(R.id.moverNameicon);
holder.masLineChart = convertView.findViewById(R.id.moversgraph);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ScripBean scripBean = Logs.allScripBean.get(arrayList.get(position));
MostActiveStockMarketFeedBean marketFeedBean = Logs.mostActiveStockMarketFeedBeanHashMap.get(arrayList.get(position));
if (marketFeedBean != null) {
changePercentage = marketFeedBean.getChange() / (marketFeedBean.getLastTradePrice() - marketFeedBean.getChange()) * 100;
holder.moverScripName.setText(marketFeedBean.getScrip());
holder.moverSymbolName.setText(marketFeedBean.getScripName());
holder.sector.setText(scripBean.getSectorName());
holder.nameIcon.setText(marketFeedBean.getScrip().substring(0,1));
holder.moverLastTradePrice.setText(Logs.priceFormat.format(marketFeedBean.getLastTradePrice()).replace("-", ""));
setData(5,3);
customiseChart();
if(marketFeedBean.getChange() != 0.0) {
if (Logs.priceFormat.format(changePercentage).contains("-")) {
holder.moverLastTradePrice.setBackground(context.getResources().getDrawable(R.drawable.bg_negativecell));
}
else
{
holder.moverLastTradePrice.setBackground(context.getResources().getDrawable(R.drawable.bg_positivecell));
}
holder.moverchange.setText(marketFeedBean.getChange() + " " + "(" + Logs.priceFormat.format(changePercentage).replace("-", "") + "%)");
}
else
{
holder.moverchange.setText("(0.00%)");
}
}
else {
String sm = arrayList.get(position);
holder.moverScripName.setText(sm.split("\\:", -1)[0]);
holder.moverMarket.setText(sm.split("\\:", -1)[1]);
holder.moverSymbolName.setText("");
holder.moverLastTradePrice.setText("0.00");
holder.moverchange.setText("0.00");
}
return convertView;
}
private void setData(int count, float range) {
values = new ArrayList<>();
for (int i = 0; i < count; i++) {
float val = (float) (Math.random() * range) - 30;
values.add(new Entry(i, val));
}
set1 = new LineDataSet(values, "DataSet 1");
set1.setDrawCircles(false);
set1.setDrawFilled(true);
set1.setLineWidth(1f);
set1.setColor(Color.GREEN);
set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set1.setDrawFilled(true);
set1.setFillDrawable(drawablePositive);
set1.setFillFormatter(new IFillFormatter() {
#Override
public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
return holder.masLineChart.getAxisLeft().getAxisMinimum();
}
});
ArrayList<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
data = new LineData(dataSets);
holder.masLineChart.setData(data);
}
private void customiseChart()
{
holder.masLineChart.getDescription().setEnabled(false);
holder.masLineChart.setDrawGridBackground(false);
holder.masLineChart.setDragEnabled(false);
holder.masLineChart.getLegend().setEnabled(false);
holder.masLineChart.setScaleEnabled(true);
holder.masLineChart.setScaleYEnabled(false);
holder.masLineChart.setScaleXEnabled(true);
holder.masLineChart.setDrawGridBackground(false);
holder.masLineChart.getXAxis().setEnabled(false);
holder.masLineChart.getLineData().setDrawValues(false);
holder.masLineChart.getXAxis().setDrawGridLines(false);
holder.masLineChart.getXAxis().setDrawAxisLine(false);
holder.masLineChart.getAxisLeft().setDrawGridLines(false);
holder.masLineChart.getAxisRight().setDrawGridLines(false);
holder.masLineChart.getAxisRight().setDrawZeroLine(true);
holder.masLineChart.getAxisLeft().setDrawZeroLine(true);
holder.masLineChart.getAxisRight().setDrawLabels(false);
holder.masLineChart.getAxisLeft().setDrawLabels(false);
holder.masLineChart.getAxisLeft().setEnabled(false);
holder.masLineChart.getAxisRight().setEnabled(true);
holder.masLineChart.getAxisRight().setZeroLineColor(Color.BLACK);
holder.masLineChart.getAxisRight().setAxisLineColor(Color.BLACK);
holder.masLineChart.setMaxHighlightDistance(150);
holder.masLineChart.setViewPortOffsets(0, 0, 0, 0);
holder.masLineChart.setTouchEnabled(false);
holder.masLineChart.setPinchZoom(false);
}
private class ViewHolder {
TextView moverSymbolName;
TextView moverMarket;
AutoResizeTextView moverScripName;
TextView moverLastTradePrice;
AutoResizeTextView moverchange;
TextView sector;
TextView nameIcon;
LineChart masLineChart;
}
P.S: this ListView is in fragment.

Android: Extending CardView which content can be expanded

I extended the android CardView to a Expandable version of it, with a header title and an icon which can be rotated.
CODE
This file(view_cardview_header.xml) contains the header of the ExpandableCardView, it should be the first child and not collapsed.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
The attrs.xml file with custom xml parameters
<resources>
<declare-styleable name="ExpandableCardView">
<attr name="expanded" format="boolean" />
<attr name="headerTitle" format="string" />
<attr name="headerIcon" format="integer" />
</declare-styleable>
</resources>
The ExpandableCardView.java class
public class ExpandableCardView extends CardView {
private static final float ROTATION_NORMAL = 0.0f;
private static final float ROTATION_ROTATED = 180f;
private static final float PIVOT_VALUE = 0.5f;
private static final long ROTATE_DURATION = 200;
private boolean isExpanded;
public ExpandableCardView(Context context) {
this(context, null);
}
public ExpandableCardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ExpandableCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ExpandableCardView, 0, 0);
String titleText = a.getString(R.styleable.ExpandableCardView_headerTitle);
final Drawable drawable = a.getDrawable(R.styleable.ExpandableCardView_headerIcon);
a.recycle();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_cardview_header, this, true);
final LinearLayout parent = (LinearLayout) getChildAt(0);
final RelativeLayout header = (RelativeLayout) parent.getChildAt(0);
final TextView titleTextView = (TextView) header.getChildAt(0);
titleTextView.setText(titleText);
final ImageView toggle = (ImageView) header.getChildAt(1);
if(drawable != null) {
toggle.setImageDrawable(drawable);
}
header.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setExpanded(toggle, !isExpanded);
onExpansionToggled(toggle);
}
});
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if(getChildAt(0) == null || getChildAt(0).equals(child)) {
super.addView(child, index, params);
} else {
((LinearLayout) getChildAt(0)).addView(child);
}
}
private void setExpanded(ImageView toggle, boolean expanded) {
isExpanded = expanded;
final LinearLayout parent = (LinearLayout) getChildAt(0);
final int childCount = parent.getChildCount();
if(expanded) {
toggle.setRotation(ROTATION_ROTATED);
for(int i = childCount - 1; i > 0; i--) {
parent.getChildAt(i).setVisibility(VISIBLE);
}
} else {
toggle.setRotation(ROTATION_NORMAL);
for(int i = 1; i < childCount; i++) {
parent.getChildAt(i).setVisibility(GONE);
}
}
}
private void onExpansionToggled(ImageView toggle) {
RotateAnimation rotateAnimation = new RotateAnimation(ROTATION_ROTATED, ROTATION_NORMAL,
RotateAnimation.RELATIVE_TO_SELF, PIVOT_VALUE, RotateAnimation.RELATIVE_TO_SELF,
PIVOT_VALUE);
rotateAnimation.setDuration(ROTATE_DURATION);
rotateAnimation.setFillAfter(true);
toggle.startAnimation(rotateAnimation);
}
}
Fragment Layout for testing the new CardView(fragment_test.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.tecdroid.views.ExpandableCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/card_margin"
android:layout_marginBottom="#dimen/card_margin"
android:layout_marginLeft="#dimen/card_margin"
android:layout_marginRight="#dimen/card_margin"
app:headerTitle="TITLE"
app:headerIcon="#mipmap/ic_action_expand">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="First inner child"/>
</com.tecdroid.views.ExpandableCardView>
</LinearLayout>
Result on Emulator
PROBLEM
As you can see on the image, the first inner child(TextView), is not placed under the Relative Layout(Header).
First i thought i have to override the onMeasure(int widthMeasureSpec, int heightMeasureSpec) method, but the ExpandableCardView extends indirect the ViewGroup, where the onMeasure(int widthMeasureSpec, int heightMeasureSpec) method does it all for me.
Maybe someone figure out what i have forgot, or did wrong.
UPDATE
Problem solved, see changes.
CardView extends FrameLayout, your header and first child are just unrelated child views. To have a spatial relation between children you need to use a LinearLayout or RelativeLayout with align-* parameters.
why not make a compound view with your cardview and a layout of your choice that contains the child view?

Cant use OnClickListener in Custom Layout in Android?

So I made my own LinearLayout because I needed a horizontal number picker. I am using this custom layout twice in my activity:
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/button_minus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="#string/lt"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="#+id/number"
android:layout_width="75dp"
android:layout_height="match_parent"
android:inputType="number"
android:gravity="center"
android:focusable="false"
android:text="0" />
<Button
android:id="#+id/button_plus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="#string/gt"
android:textSize="30sp"
android:textStyle="bold" />
</LinearLayout>
JAVA:
public class NumberPickerHorizontal extends LinearLayout
{
private final EditText number;
private final Button button_minus, button_plus;
public NumberPickerHorizontal(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.numberpicker_horizontal, this, true);
number = (EditText) findViewById(R.id.number);
button_minus = (Button) findViewById(R.id.button_minus);
button_minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int count = Integer.parseInt(number.getText().toString());
number.setText(count--);
}
});
button_plus = (Button) findViewById(R.id.button_plus);
button_plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int count = Integer.parseInt(number.getText().toString());
number.setText(count++);
}
});
}
}
You'll notice I'm trying to activate the onClick methods for the plus and minus buttons... However, when I actually click the buttons, I get the following error:
android.content.res.Resources$NotFoundException: String resource ID #0x0
Not quite sure what I'm doing wrong.
You are trying to setText for 0, which should be an string resource(int).
Also your new increased value is never used. Increase count before setting the text. Then use setText(String.valueOf(increased count value)).
You should do this:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="#+id/button_minus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="#string/lt"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="#+id/number"
android:layout_width="75dp"
android:layout_height="match_parent"
android:inputType="number"
android:gravity="center"
android:focusable="false"
android:text="0" />
<Button
android:id="#+id/button_plus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="#string/gt"
android:textSize="30sp"
android:textStyle="bold" />
</merge>
Java:
public class NumberPickerHorizontal extends LinearLayout
{
private final EditText number;
private final Button button_minus, button_plus;
#Override
public NumberPickerHorizontal(Context context) {
super(context);
init(context);
}
#Override
public NumberPickerHorizontal(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init(context);
}
#TargetApi(11)
#Override
public NumberPickerHorizontal(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
#TargetApi(21)
#Override
public NumberPickerHorizontal(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
//android:layout_width="match_parent"
//android:layout_height="wrap_content"
//set these where you instantiate the view, XML or code!
this.setOrientation(LinearLayout.HORIZONTAL);
LayoutInflater.from(context).inflate(R.layout.numberpicker_horizontal, this, true);
number = (EditText) findViewById(R.id.number);
button_minus = (Button) findViewById(R.id.button_minus);
button_minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int count = Integer.parseInt(number.getText().toString());
count--;
number.setText(String.valueOf(count));
}
});
button_plus = (Button) findViewById(R.id.button_plus);
button_plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int count = Integer.parseInt(number.getText().toString());
count++;
number.setText(String.valueOf(count));
}
});
}
So the changes were:
1.) added <merge> to remove the duplicate layout
2.) added the remaining 3 constructors for the view in case the framework calls them
3.) added String.valueOf() around your int so that it's not perceived as a resource identifier by setText().
Try this:
View v = LayoutInflater.from(context).inflate(R.layout.numberpicker_horizontal, this, true);
And replace all findViewById by v.findViewById

setMinimumHeight() on LinearLayout isn't working (in subclass)

I have a subclass of a liner layout (referenced from XML custom type) The minimum height I've tried to set just isn't working nor is setting the layout. I need to do this programatically...
Why isn't setMinimumHeight() working?
NB: The complexity of the code can be ignored, the value it is setting is 70
public class SummaryDynamicSpacer extends LinearLayout {
private static final String TAG = "mymeter-DynamicSpacer";
int dpWidth = 0;
int dpHeight = 0;
public SummaryDynamicSpacer(Context context) {
super(context);
init(context);
}
public SummaryDynamicSpacer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
//Set dpWidth, this is the key metric we use for scaling.
float density = getResources().getDisplayMetrics().density;
float dpWidth = metrics.widthPixels / density;
float dpHeight = metrics.heightPixels / density;
this.dpWidth = (int)dpWidth;
this.dpHeight = (int)dpHeight;
Log.d(TAG, "zyxHeightDP: "+metrics.heightPixels / density);
int id = this.getId();
int increment = 10;
int adjustment = getValueForLargeDevice(increment);
if(id == R.id.betweenAddressAndTopBox) {
doBetweenAddressAndTopBox(context, adjustment);
} else if(id == R.id.betweenTopAndAddress) {
doBetweenTopAndAddress(context, adjustment);
}
Log.d(TAG, "SettingHeight: "+adjustment);
this.setBackgroundColor(Color.BLUE);
}
private void doBetweenAddressAndTopBox(Context context, int adjustment) {
this.setMinimumHeight(adjustment);
}
private void doBetweenTopAndAddress(Context context, int adjustment) {
this.setMinimumHeight(adjustment);
}
private int getValueForLargeDevice(double increment) {
int largeDeviceAdjustment = 0;
if(dpHeight > 750) {
int difference = (int)dpHeight - 750;
int interval = 25;
int iterations = (difference / interval) > 12 ? 12 : (difference / interval);
int increasePerInterval = 0;
for(int i=0; i < iterations; i++) {
largeDeviceAdjustment += increment;
}
return largeDeviceAdjustment;
} else {
return 1;
}
}
}
I think your code is fine. Your layout likely has an issue. Did you set the layout as follows?
<com.example.dynamicspacerlayout.SummaryDynamicSpacer
android:id="#+id/betweenAddressAndTopBox"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
See this also does minHeight do anything?
GalaxyNexus Screen Shot running your code
Nexus7 Screen Shot
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Top Text">
<requestFocus />
</EditText>
<com.example.dynamicspacerlayout.SummaryDynamicSpacer
android:id="#+id/betweenAddressAndTopBox"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#android:color/white"
/>
</com.example.dynamicspacerlayout.SummaryDynamicSpacer>
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Bottom Text"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
int minimumHeight = findViewById(R.id.betweenAddressAndTopBox).getHeight();
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Height: " + minimumHeight);
// text.setVisibility(minimumHeight > 1 ? View.VISIBLE : View.GONE);
}
}, 1000);
}
}
Hope that Helps!

How to zoom in/zoom out by increasing a layout or textView text size in **android**?

Here is the bellow code and in want to make a zoom in and out facilities by using the zoom in and out button form android.
public class ShowDescription extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
new LoadDetails(this).execute();
super.onCreate(savedInstanceState);
setContentView(R.layout.showdescription);
String theStory = null;
String pubDate = null;
String storyTitle = null;
String writer = null;
//String test = null;
Intent intent = getIntent();
if (intent != null) {
Bundle b = intent.getExtras();
if (b == null) {
theStory = "bad bundle?";
} else {
storyTitle =ComplexScript.UTF2ANSI(ComplexScript.swap(b.getString("title")))+"\n\n";
//pubDate=ComplexScript.UTF2ANSI(ComplexScript.swap(ComplexScript.Replace(b.getString("pubdate"))))+ "\n\n";
pubDate=ComplexScript.Replace(b.getString("pubdate"))+"\n";
writer=ComplexScript.UTF2ANSI(ComplexScript.swap(b.getString("writers")))+",\n"+ComplexScript.UTF2ANSI(ComplexScript.swap(b.getString("initial")))+"\n";
theStory =ComplexScript.UTF2ANSI(ComplexScript.swap(b.getString("description"))).replace('\n', ' ').replaceAll(" "," ").replaceAll("‘","Ô").replaceAll("’","Õ");
//+ "\n\nMore information:\n" + b.getString("link");
//test=b.getString("image");
}
} else {
theStory = "Information not found.";
}
//Bitmap bimage= getBitmapFromURL(test);
//iv.setImageBitmap(bimage);
Typeface tf = Typeface.createFromAsset(getAssets(),
"font/SutonnyMJ.ttf");
TextView story = (TextView)findViewById(R.id.storybox);
story.setText(Html.fromHtml("<h1><font color='#B10000'>"+storyTitle+"</font></h1><small>"+pubDate+"<br/>"+writer+"</small><p>"+theStory+"</p>"));
story.setTypeface(tf);
story.setLineSpacing(1,(float) 1.5);
TextView moto =(TextView)findViewById(R.id.moto);
moto.setText("msev` we‡bv`b mviv¶Y");
moto.setTypeface(tf);
Button backButton = (Button)findViewById(R.id.back);
backButton.setTypeface(tf);
TextView tv = (TextView) findViewById(R.id.footer);
tv.setTypeface(tf);
backButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
finish();
}
});
}}
And here below is the XML file
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFF" android:orientation="vertical">
<ImageView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#86878A"
android:contentDescription="#string/app_name"
android:src="#drawable/logobn24"/>
<TextView android:id="#+id/moto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#86878A"
android:textColor="#FFF"
android:gravity="center"/>
<TextView android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#86878A"/>
<ScrollView android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFF"
android:orientation="vertical" >
<!-- android:textColor="#4e4e4e" -->
<ImageView android:id="#+id/img"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:contentDescription="#string/des"/>
<TextView android:id="#+id/storybox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/img"
android:background="#FFFFFF"
android:paddingLeft="10dp"
android:textColor="#000"
android:textSize="18dp"
android:paddingTop="10dp"/>
</RelativeLayout>
</ScrollView>
<Button android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/back"/>
<TextView android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#86878A"
android:gravity="center_vertical|center_horizontal"
android:text="#string/footer"
android:textColor="#FFF" android:lineSpacingMultiplier="1.3"/>
Can any one make a zoom in and zoom out facilities udder this class? or just increase or decrease the text size of Text View story? Can any one help me?
What happens if you call the methods of TextView?
public void setScaleX(float scaleX)
public void setScaleY(float scaleY)
This may help you...
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.TextView;
public class ResizableTextViewW extends TextView {
private static final int INVALID_POINTER_ID = -1;
public static final String TAG = ResizableTextViewW.class.getSimpleName();
private float mLastTouchX;
private float mLastTouchY;
private int mActivePointerId = INVALID_POINTER_ID;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
private int count = 0;
public float mPreviousScaleFactor = 1.f;
public ResizableTextViewW(Context context) {
this(context, null, 0);
}
public ResizableTextViewW(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ResizableTextViewW(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.setText(String.valueOf(count));
this.setTextSize(10+count);
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
if (mScaleFactor > mPreviousScaleFactor) {
count = count + 1;
invalidate();
} else if (mScaleFactor < mPreviousScaleFactor) {
if (count > 0) {
count = count - 1;
invalidate();
}
}
mPreviousScaleFactor = mScaleFactor;
return true;
}
}

Categories